package projorientado.anpr.impl;

import java.util.Iterator;
import projorientado.anpr.OCRPlate;
import projorientado.anpr.OCRPlateProvider;
import projorientado.ocr.OCRProvider;
import projorientado.ocr.OCRecognizer;
import projorientado.spi.ServiceProvider;
import projorientado.util.CodeTokenizer;
import projorientado.util.CodeTokenizer.CodeElement;
import projorientado.util.CodeTokenizer.CodeLine;
import projorientado.util.CodeTokenizer.CodeVarDef;

public class FormatedOCRPlateProvider implements ServiceProvider<OCRPlate> {

    private static final FormatedOCRPlateProvider instance = new FormatedOCRPlateProvider();
    
    static {
        OCRPlateProvider.getInstance().registerServiceProvider("formatedOCRPlate", instance);
    }
    
    private FormatedOCRPlateProvider() {
        
    }
    
    public static FormatedOCRPlateProvider getInstance() {
        return instance;
    }
    
    public OCRPlate getService(String s) {
        
        OCRecognizer ocr = null;
        String format = "";
        
        CodeTokenizer.CodeBlock root = CodeTokenizer.singleParse(s);
        
        Iterator<CodeTokenizer.CodeElement> it = root.childs.iterator();
        while(it.hasNext()) {
            CodeElement e = it.next();
            if(e instanceof CodeTokenizer.CodeTextBlock) {
                CodeTokenizer.CodeTextBlock tblock = (CodeTokenizer.CodeTextBlock)e;
                String name = tblock.name.toLowerCase();
                
                if(name.startsWith("ocr:") || name.startsWith("ocrecognizer:")) {
                    String service = tblock.name.substring(name.indexOf(':')+1);
                    ocr = OCRProvider.getOCR(service, tblock.text);
                }
            } else if(e instanceof CodeTokenizer.CodeLine) {
                CodeVarDef var = CodeTokenizer.parseVarDef(((CodeLine)e).line);
                if(var.varName.equalsIgnoreCase("format")) {
                    format = var.value;
                }
            }
        }
        
        return new FormatedOCRPlate(ocr,format);
    }

}
